Online-Academy
Look, Read, Understand, Apply

File and Writing Java Object to File

File

File class is neither byte stream nor character stream. it represents a file or directory path and provides information about it (name, path, size, permissions, etc.).

We can use FileWriter object to write characters / text to a file. It is a Character stream.

Java ClassTypePurpose
FileNeitherRepresents a file/directory
FileInputStreamByte StreamReads raw bytes
FileOutputStreamByte StreamWrites raw bytes
FileReaderCharacter StreamReads Characters
FileWriterCharacter StreamWrites Characters

Writing Objet to File

We can write an actual Java object to a file and later reconstruct that object using

  • ObjectOutputStream -> Writes the object
  • ObjectInputStream -> reads teh object
  • import java.io.*;
    
    class Student implements Serializable {
        int id;
        String name;
    
        Student(int id, String name) {
            this.id = id;
            this.name = name;
        }
    }
    
    public class Main {
        public static void main(String[] args) throws Exception {
    
            Student s = new Student(101, "Ram");
    
            // Write object
            ObjectOutputStream out =
                new ObjectOutputStream(new FileOutputStream("student.dat"));
    
            out.writeObject(s);
            out.close();
    
            // Read object
            ObjectInputStream in =
                new ObjectInputStream(new FileInputStream("student.dat"));
    
            Student s2 = (Student) in.readObject();
            in.close();
    
            System.out.println(s2.id);
            System.out.println(s2.name);
        }
    }    
    

    We cannot use a character stream to read / write Java object to a file. FileWriter and FileReader are designed for characters/text, whereas, serialized Java object is represented as binary data.

    Objects can be stored as text. We can convert an object's data into a text format, such as JSON, and then use character streams.